package poly2;

import java.util.Scanner;

class Polynomial {

	public termNode head;

	public Polynomial() {
		head = null;
	}

	public boolean isEmpty() {
		return (head == null);
	}

	public void display() {
		if (head == null)
			System.out.print("0");
		else
			for (termNode cur = head; cur != null; cur = cur.getNext()) {
				System.out.println(cur);
			}
	}

	public void insert(termNode newNode) {
		termNode prev = null;
		termNode cur = head;
		while (cur != null && (newNode.compareTo(cur) < 0)) {
			prev = null;
			cur = cur.getNext();
		}
		if (prev == null) {
			newNode.setNext(head);
			head = newNode;
		} else {
			newNode.setNext(cur);
			prev.setNext(newNode);
		}
	}

	public void readPolynomial(Scanner kb) {
		boolean done = false;
		double coefficient;
		int exponent;
		termNode term;
		head = null; // UNLINK ANY PREVIOUS POLYNOMIAL
		System.out.println("Enter 0 and 0 to end.");
		System.out.print("coefficient: ");
		coefficient = kb.nextDouble();
		System.out.println(coefficient);
		System.out.print("exponent: ");
		exponent = kb.nextInt();
		System.out.println(exponent);
		done = (coefficient == 0 && exponent == 0);
		while (!done) {
			Polynomial poly = new Polynomial();
			term = new termNode(coefficient, exponent);
			System.out.println(term);
			poly.insert(term);

			System.out.println("Enter 0 and 0 to end.");
			System.out.print("coefficient: ");
			coefficient = kb.nextDouble();
			System.out.println(coefficient);
			System.out.print("exponent: ");
			exponent = kb.nextInt();
			System.out.println(exponent);
			done = (coefficient == 0 && exponent == 0);
		}
	}

	public static Polynomial add(Polynomial p, Polynomial q) {
		Polynomial r = new Polynomial();
		double coefficient;
		int exponent;
		termNode first = p.head;
		termNode second = q.head;
		termNode sum = r.head;
		termNode term;
		while (first != null && second != null) {
			if (first.getExp() == second.getExp()) {
				if (first.getCoeff() != 0 && second.getCoeff() != 0)
					;
				{
					double addCoeff = first.getCoeff() + second.getCoeff();
					term = new termNode(addCoeff, first.getExp());
					sum.setNext(term);
					first.getNext();
					second.getNext();
				}
			} else if (first.getExp() < second.getExp()) {
				sum.setNext(second);
				term = new termNode(second.getCoeff(), second.getExp());
				sum.setNext(term);
				second.getNext();
			} else {
				sum.setNext(first);
				term = new termNode(first.getNext());
				sum.setNext(term);
				first.getNext();
			}
		}
		while (first != null) {
			sum.setNext(first);
		}
		while (second != null) {
			sum.setNext(second);
		}
		return r;
	}
}